package servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * @description: 分发器
 * @author: 王代涛
 * @create: 2021-04-18 19:34
 **/

@SuppressWarnings("JavaDoc")
public class DispatcherServlet extends HttpServlet {

    /**
     * request请求参数
     */
    protected HttpServletRequest request;

    /**
     * response返回参数
     */
    protected HttpServletResponse response;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置头信息
        response.setHeader("Access-Control-Allow-Origin", ResourceBundle.getBundle("resource").getString("Origin"));
        response.setHeader("Access-Control-Allow-Headers", ResourceBundle.getBundle("resource").getString("Headers"));
        response.setHeader("Access-Control-Allow-Methods", ResourceBundle.getBundle("resource").getString("Methods"));
        response.setHeader("Content-Type",ResourceBundle.getBundle("resource").getString("Content-Type"));
        // 设置编码
        request.setCharacterEncoding(ResourceBundle.getBundle("resource").getString("CharacterEncoding"));
        response.setCharacterEncoding(ResourceBundle.getBundle("resource").getString("CharacterEncoding"));

        this.request = request;
        this.response = response;

        String status = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);

        if (!Objects.equals(status,"")){
            try {
                //分发器
                Method met = this.getClass().getMethod(status);
                met.invoke(this);
            } catch (Exception e) {
                //
            }
        }
    }
}
